package com.quercus.dao.impl;

import com.quercus.dao.UserDao;
import com.quercus.entity.User;
import com.quercus.util.XmlUtil;
import org.dom4j.Document;
import org.dom4j.Element;

import java.util.List;

/**
 * @author quercus
 */
public class UserDaoImpl implements UserDao {
    private String fileName;

    public UserDaoImpl() {
    }

    public UserDaoImpl(String fileName) {
        this.fileName = fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    Document doc;

    @Override
    public User findUser(String userId, String password) {
        doc = XmlUtil.readFile(fileName);
        User user = null;

        //获取DOM树的根元素users
        Element root = doc.getRootElement();
        //获取根元素users的子元素user
        List<Element> userList = root.elements("user");
        for (Element userElem : userList) {
            Element userIdElem = userElem.element("userId");
            //如果用户编号相同
            if (userId.equals(userIdElem.getText())) {
                Element pwdElem = userElem.element("password");
                //如果密码也相同
                if (password.equals(pwdElem.getText())) {
                    //如果还不是离职状态
                    Element statusElem = userElem.element("status");
                    int status = Integer.parseInt(statusElem.getText());
                    if (1 == status) {
                        //那就登录成功了，根据XML内容创建User对象
                        String realName = userElem.element("realName").getText();
                        String phone = userElem.element("phone").getText();
                        user = new User(userId, realName, password, phone, status);
                        //跳出循环
                        break;
                    }
                }
            }
        }
        return user;
    }
}